# -*- codeing = utf-8 -*-
# @Time : 2024/7/23 14:56
# @Author : 袁美玉
# @File : demo2_百度爬取周杰伦照片.py
# @Software  ：PyCharm
"""
爬取10张周杰伦照片
"""
import os

import requests

keyword = "周杰伦"
if not os.path.exists(keyword):
    os.makedirs(keyword)
url = "https://image.baidu.com/search/acjson?tn=resultjson_com&logid=9597543001464091378&ipn=rj&ct=201326592&is=&fp=result&fr=&word=%E5%91%A8%E6%9D%B0%E4%BC%A6&cg=star&queryWord=%E5%91%A8%E6%9D%B0%E4%BC%A6&cl=&lm=&ie=utf-8&oe=utf-8&adpicid=&st=&z=&ic=&hd=&latest=&copyright=&s=&se=&tab=&width=&height=&face=&istype=&qc=&nc=&expermode=&nojc=&isAsync=&pn=90&rn=30&gsm=5a&1721717917373="
headers = {
    "Cookie":
        "BDIMGISLOGIN=0; winWH=%5E6_1872x966; BDqhfp=%E9%9B%AA%E5%B1%B1%26%26NaN-1undefined%26%263264%26%263; BIDUPSID=54EC44A93059F856AD40192B12CC9E37; PSTM=1720771497; BAIDUID=54EC44A93059F856D9A123344394C7EE:FG=1; BAIDUID_BFESS=54EC44A93059F856D9A123344394C7EE:FG=1; ZFY=o:AAaGy:AguPRjYq8FEQwXspbStdfLvsqlep7ZicO9XPs:C; newlogin=1; ZD_ENTRY=other; BDRCVFR[dG2JNJb_ajR]=mk3SLVN4HKm; BDRCVFR[-pGxjrCMryR]=mk3SLVN4HKm; H_WISE_SIDS=60359_60492_60502; BDRCVFR[tox4WRQ4-Km]=mk3SLVN4HKm; H_PS_PSSID=60359_60492_60502; BA_HECTOR=0k848g2k2g81a40g010ka0853g90de1j9uilv1v; PSINO=1; delPer=0; H_WISE_SIDS_BFESS=60359_60492_60502; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; userFrom=www.baidu.com; ab_sr=1.0.1_YTMwMjM5ODViZjFjMzU2ZGE5MGE0MjE4NTg4NzJhN2EwZjRmOTY0MDZlYjRiMGI3NmQ4ZGFiNTU5ZTE5ZWExNWVlODJjMWU5ODQxMjE0ZGU2ZDEwYmI4MWZhMzNlMzcxNDllNTA2NDgxMGY2NjM0ZmFjNWJlY2ViMDNiZGZkN2UxYWJhYTY1OTNmN2RjNzI3NzdiMzYxMjY3OWQyZTcyOQ==",
    "Host":
        "image.baidu.com",
    "Referer":
        "https://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&dyTabStr=MCwxLDMsMiw0LDYsNSw3LDgsOQ%3D%3D&word=%E9%9B%AA%E5%B1%B1",
    "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0"
}

response = requests.get(url=url, headers=headers)
# print(type(response)) # <class 'requests.models.Response'>
json_data = response.json()  # 转换成了json格式 {'queryEnc': '%D6%DC%BD%DC%C2%D7',}
# print(json_data)
data_list = json_data['data']  # 这一页中的所有图片的data信息，要对每一个图片进行遍历
number = 1
for data in data_list:
    img_url = data['middleURL']  # 获得图片的路径地址
    img = requests.get(img_url).content  # 请求这个路径，得到图片。将内容显示出来
    # 现在需要吧这个图片保存在指定文件夹下，命名为:周杰伦1.jpg
    name = r"%s/%s_%d.jpg" % (keyword, keyword, number)
    with open(name, mode='wb') as f:
        f.write(img)
    number += 1
    if number >= 11:
        break
